from system.host.models import Host
from system.host.serializers import HostSerializer, HostCreateUpdateSerializer
from utils.viewset import CustomModelViewSet
from utils.json_response import SuccessResponse
from utils.tools import AttrDict
from openpyxl import load_workbook
from rest_framework.parsers import MultiPartParser
from rest_framework.views import APIView


class HostModelViewSet(CustomModelViewSet):
    """
    主机管理 的CRUD视图
    """
    queryset = Host.objects.all()
    serializer_class = HostSerializer
    create_serializer_class = HostCreateUpdateSerializer
    update_serializer_class = HostCreateUpdateSerializer
    search_fields = ('ip', 'hostname')


class FileUploadView(APIView):
    parser_classes = (MultiPartParser,)

    def post(self, request):
        file = request.data['file']
        group_id = request.data['group']
        ws = load_workbook(file, read_only=True)['Sheet1']
        summary = {'invalid': [], 'skip': [], 'repeat': [], 'success': []}
        for i, row in enumerate(ws.rows):
            if i == 0:  # 第1行是表头 略过
                continue
            if not all([row[x].value for x in range(4)]):
                summary['invalid'].append(i)
                continue
            data = AttrDict(
                hostname=row[0].value,
                ip=row[1].value,
                port=row[2].value,
                username=row[3].value,
                desc=row[4].value,
                group_id=group_id,
            )
            if Host.objects.filter(ip=data.ip, port=data.port, username=data.username).exists():
                summary['skip'].append(i)
                continue
            if Host.objects.filter(hostname=data.hostname).exists():
                summary['repeat'].append(i)
                continue
            Host.objects.create(creator=request.user, **data)
            summary['success'].append(i)
        return SuccessResponse(data=summary)
